package com.xcf.codec;

import com.alibaba.fastjson.JSON;
import com.xcf.model.RpcRequest;
import com.xcf.model.RpcResponse;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

import java.util.concurrent.Callable;

/**
 * Json 编码器
 */
public class RequestJsonEncoder extends MessageToByteEncoder<RpcRequest> {

    private final Callable callable;

    public RequestJsonEncoder(Callable callable) {
        this.callable = callable;
    }

    @Override
    protected void encode(ChannelHandlerContext ctx, RpcRequest msg, ByteBuf out) throws Exception {
        try {
            byte[] bytes = JSON.toJSONBytes(msg);
            out.writeInt(bytes.length);
            out.writeBytes(bytes);
        } catch (Throwable throwable) {
            synchronized (callable) {
                callable.notify();
            }
            throw throwable;
        }
    }

}
